package com.macbulldev.poc.testgin.controller;

import java.util.Date;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.macbulldev.poc.testgin.domain.AppUser;
import com.macbulldev.poc.testgin.domain.EventLog;
import com.macbulldev.poc.testgin.domain.PolicyType;
import com.macbulldev.poc.testgin.domain.Scenario;
import com.macbulldev.poc.testgin.domain.Underwriter;
import com.macbulldev.poc.testgin.service.WebappUtils;


@org.springframework.roo.addon.web.mvc.controller.RooWebScaffold(path = "policytype", automaticallyMaintainView = false, formBackingObject = com.macbulldev.poc.testgin.domain.PolicyType.class)
@org.springframework.web.bind.annotation.RequestMapping("/policytype/**")
@org.springframework.stereotype.Controller
public class PolicyTypeController {
	
	
	private static final Logger LOGGER = Logger.getLogger(PolicyType.class);
	
	@RequestMapping(value = "/policytype/list", method = RequestMethod.GET)    
    public String renderPolicyTypeList(@RequestParam(value = "pageNumber", required = false) Integer page, ModelMap modelMap) {    
		
		int sizeNo = 20;           
        int pageNumber= page == null ? 0 : page;
        
        modelMap.addAttribute("policytypes",PolicyType.findPolicyTypeEntries(pageNumber*sizeNo, sizeNo));            
        Long count = PolicyType.countPolicyTypes();
        modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        return "policytype/list";        
    }
	
	

	@RequestMapping(value = "/policytype", method = RequestMethod.POST)    
    public String create(@Valid PolicyType policyType, BindingResult result, ModelMap modelMap,HttpSession session) {    
        if (policyType == null) throw new IllegalArgumentException("A policyType is required");        
        
        if(PolicyType.findPolicyTypeByDisplayNameAndAbbrName(policyType.getDisplayName(), policyType.getAbbrName()) != null)
        {
        	result.addError(new FieldError("policyType","displayName","This Policy Type Already Exist and you May not have Duplicates"));
        }
        
        if (result.hasErrors()) {        
            modelMap.addAttribute("policyType", policyType);            
            modelMap.addAttribute("scenarios", Scenario.findAllScenarios());            
            return "policytype/create";            
        }
        
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        policyType.setCreateUsername(sessionUser.getName());
    	policyType.setUpdateUsername(sessionUser.getName());
    	policyType.setCreateTs(new Date());
		policyType.setUpdateTs(new Date());
		
		EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(PolicyType.class.getSimpleName());
    	log.setOperation("PolicyType "+ policyType.getDisplayName()+" Created");
    	log.persist();
        
        
        policyType.persist();        
        return "redirect:/policytype/" + policyType.getId();        
    }

	@RequestMapping(value = "/policytype/form", method = RequestMethod.GET)    
    public String createForm(ModelMap modelMap) {    
        modelMap.addAttribute("policyType", new PolicyType());        
        modelMap.addAttribute("scenarios", Scenario.findAllScenarios());        
        return "policytype/create";        
    }

	@RequestMapping(value = "/policytype/{id}", method = RequestMethod.GET)    
    public String show(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("policyType", PolicyType.findPolicyType(id));        
        return "policytype/show";        
    }

	@RequestMapping(value = "/policytype", method = RequestMethod.GET)    
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, ModelMap modelMap) {    
        if (page != null || size != null) {        
            int sizeNo = size == null ? 10 : size.intValue();            
            modelMap.addAttribute("policytypes", PolicyType.findPolicyTypeEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));            
            float nrOfPages = (float) PolicyType.countPolicyTypes() / sizeNo;            
            modelMap.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));            
        } else {        
            modelMap.addAttribute("policytypes", PolicyType.findAllPolicyTypes());            
        }        
        return "policytype/list";        
    }

	@RequestMapping(method = RequestMethod.PUT)    
    public String update(@Valid PolicyType policyType, BindingResult result, ModelMap modelMap,HttpSession session) {    
        if (policyType == null) throw new IllegalArgumentException("A policyType is required");        
        if (result.hasErrors()) {        
            modelMap.addAttribute("policyType", policyType);            
            modelMap.addAttribute("scenarios", Scenario.findAllScenarios());            
            return "policytype/update";            
        }
        
        
        policyType.setCreateUsername(PolicyType.findPolicyType(policyType.getId()).getCreateUsername());
        policyType.setCreateTs(PolicyType.findPolicyType(policyType.getId()).getCreateTs());
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        policyType.setUpdateUsername(sessionUser.getName());
        policyType.setUpdateTs(new Date());

        policyType.merge();
        
        
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(PolicyType.class.getSimpleName());
    	log.setOperation("PolicyType "+ policyType.getDisplayName()+" Updated");
    	log.persist();
        
        
        return "redirect:/policytype/" + policyType.getId();        
    }

	@RequestMapping(value = "/policytype/{id}/form", method = RequestMethod.GET)    
    public String updateForm(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("policyType", PolicyType.findPolicyType(id));        
        modelMap.addAttribute("scenarios", Scenario.findAllScenarios());        
        return "policytype/update";        
    }

	@RequestMapping(value = "/policytype/{id}", method = RequestMethod.DELETE)    
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size,HttpSession session) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(PolicyType.class.getSimpleName());
    	log.setOperation("PolicyType "+ PolicyType.findPolicyType(id).getDisplayName()+" Deleted");
    	log.persist();
        
        
        PolicyType.findPolicyType(id).remove();

        return "redirect:/policytype?page=" + ((page == null) ? "1" : page.toString()) + "&size=" + ((size == null) ? "10" : size.toString());        
    }
}
